
package com.eworking.eim.notify;

import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

import com.eworking.eim.EIMChatManager;
import com.eworking.eim.EIMChatOptions;
import com.eworking.eim.EIMConstants;
import com.eworking.eim.message.EIMMessage;
import com.eworking.eim.message.EIMMessageEncoder;
import com.eworking.eim.util.EIMLog;
import com.eworking.eim.util.EasyUtil;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Vibrator;

public class EIMNotifyManager {
    
    /** 日志输出标记 */
    private static final String _TAG = EIMNotifyManager.class.getSimpleName();
    
    /** 消息提示信息 -英文 */
    private static final String[] _MSG_EN = { "sent a message", "sent a picture", "sent a voice",
        "sent location message", "sent a video", "sent a file", "%1 contacts sent %2 messages" };
    
    /** 消息提示信息 - 中文 */
    private static final String[] _MSG_CH = { "发来一条消息", "发来一张图片", "发来一段语音", "发来位置信息", "发来一个视频", "发来一个文件",
        "[1]个联系人发来[2]条消息" };
    
    private static EIMNotifyManager notifyManager = null;
    
    private static int notifyID = 341;
    
    private Context context = null;
    
    /** 最后通知时间 */
    private long lastNotifyTime = 0;
    
    /** 消息提示铃声 */
    private static Ringtone ringtone = null;
    
    /** 消息提示信息 */
    private String[] msgs = null;
    
    private EIMMessageNotifyListener messageNotifyListener = null;
    
    private NotificationManager notificationManager = null;
    
    /** 应用名称 */
    private String appName = "";
    
    /** 应用包名称 */
    private String packageName = "";
    
    /** 消息发送人集合 */
    private Set<String> fromUsers = new HashSet<String>();
    
    /** 通知消息数量 */
    private int notificationNum = 0;
    
    public EIMNotifyManager(Context context) {
        this.context = context;
        this.messageNotifyListener = EIMChatManager.getInstance().getChatOptions().getMessageNotifyListener();
        this.notificationManager = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
        // 语言(中文or英文)
        if (Locale.getDefault().getLanguage().equals("zh")) {
            this.msgs = _MSG_CH;
        } else {
            this.msgs = _MSG_EN;
        }
        // 应用名称
        if (this.context.getApplicationInfo().labelRes != 0) {
            this.appName = this.context.getString(this.context.getApplicationInfo().labelRes);
        }
        // 应用包名称
        this.packageName = this.context.getApplicationInfo().packageName;
    }
    
    public static synchronized EIMNotifyManager getInstance(Context context) {
        if (notifyManager == null) {
            notifyManager = new EIMNotifyManager(context);
        }
        return notifyManager;
    }
    
    /**
     * 消息通知
     * 
     * @param message
     */
    public void notifyMessage(EIMMessage message) {
        // 新消息通知
        this.notifyNewMessage();
        // 是否正在运行前台
        if (!EasyUtil.isAppRunningForeground(context)) {
            // 如果没有运行,则推送消息提示
            this.sendNotification(message);
        } else {
            // 如果在运行，则推送一条广播消息
            this.sendBroadcast(message);
        }
    }
    
    /**
     * 发送回执广播消息
     * 
     * @param account 用户账号
     * @param msgId 消息ID
     */
    public void notifyAckMessage(String account, String msgId) {
        Intent localIntent = new Intent(EIMConstants._ACK_MSG_BROADCAST);
        localIntent.putExtra("msgid", msgId);
        localIntent.putExtra("from", account);
        EIMLog.d(_TAG, "发送一条回执的广播消息:" + msgId);
        this.context.sendOrderedBroadcast(localIntent, null);
    }
    
    /**
     * 发送消息广播
     * 
     * @param message 消息实体
     */
    private void sendBroadcast(EIMMessage message) {
        Intent intent = new Intent(EIMConstants._NEW_MSG_BROADCAST);
        intent.putExtra("msgid", message.msgId);
        intent.putExtra("from", message.from.getAccount());
        intent.putExtra("type", message.type.ordinal());
        intent.putExtra("body", EIMMessageEncoder.convertMsgToJSON(message, false));
        EIMLog.d(_TAG, "发送一条新的广播消息" + message.msgId);
        this.context.sendOrderedBroadcast(intent, null);
    }
    
    /**
     * 发送通知(程序没有运行时)
     * 
     * @param message
     */
    @SuppressLint("NewApi")
	private void sendNotification(EIMMessage message) {
        // 消息发送人昵称
        String strNickName = message.from.getNickname();
        String strMsg = strNickName + " ";
        switch (message.type.ordinal()) {
            case 1:
                strMsg = strMsg + this.msgs[0];
                break;
            case 2:
                strMsg = strMsg + this.msgs[1];
                break;
            case 5:
                strMsg = strMsg + this.msgs[2];
                break;
            case 4:
                strMsg = strMsg + this.msgs[3];
                break;
            case 3:
                strMsg = strMsg + this.msgs[4];
                break;
            case 6:
                strMsg = strMsg + this.msgs[5];
        }
        // 自定义消息通知内容
        if (this.messageNotifyListener != null) {
            strMsg = this.messageNotifyListener.onNewMessageNotify(message);
        }
        // 设置通知信息对象
        Builder builder = new Notification.Builder(context);
        builder.setSmallIcon(this.context.getApplicationInfo().icon);
        builder.setTicker(strMsg);
        builder.setWhen(System.currentTimeMillis());
        
        Intent intent = this.context.getPackageManager().getLaunchIntentForPackage(this.packageName);
        EIMChatOptions chatOptions = EIMChatManager.getInstance().getChatOptions();
        if (chatOptions.getNotificationClickListener() != null) {
            intent = chatOptions.getNotificationClickListener().onNotificationClick(message);
        }
        PendingIntent pendingIntent =
            PendingIntent.getActivity(this.context, notifyID, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        // 通知消息数量
        this.notificationNum++;
        this.fromUsers.add(message.getFrom());
        // 替换消息中的占位符
        String sumMsg = this.msgs[6].replaceAll("[1]", String.valueOf(this.fromUsers.size()));
        if (this.messageNotifyListener != null) {
            // 最新的消息通知
            sumMsg =
                this.messageNotifyListener.onLatestMessageNotify(message, this.fromUsers.size(), this.notificationNum);
        }
        
        builder.setContentTitle(this.appName);
        builder.setContentText(sumMsg);
        builder.setContentIntent(pendingIntent);
        builder.setAutoCancel(true);
        builder.setNumber(notificationNum);
        // 通知消息
        this.notificationManager.notify(notifyID, builder.build());
    }
    
    /**
     * 新消息通知
     */
    public void notifyNewMessage() {
        EIMChatOptions chatOptions = EIMChatManager.getInstance().getChatOptions();
        if (!chatOptions.getNotificationEnable()) {
            EIMLog.d(_TAG, "消息通知未启用");
            return;
        }
        try {
            long currentTime = System.currentTimeMillis();
            if (currentTime - this.lastNotifyTime < 1000) {
                return;
            }
            this.lastNotifyTime = currentTime;
            // 振动提示
            if (chatOptions.getNoticedByVibrate()) {
                // 启动振动，设置振动时长
                Vibrator vibrator = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(500);
            }
            if (chatOptions.getNoticedBySound()) {
                if (ringtone == null) {
                    // 获取默认的铃声
                    Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                    ringtone = RingtoneManager.getRingtone(context, uri);
                    if (ringtone == null) {
                        EIMLog.d(_TAG, "没有发现可使用的铃声");
                        return;
                    }
                }
                // 播放铃声
                if (!ringtone.isPlaying()) {
                    ringtone.play();
                    String manufacturer = Build.MANUFACTURER;
                    if (manufacturer != null && manufacturer.contains("samsung")) {
                        new Thread(new Runnable() {
                            
                            @Override
                            public void run() {
                                try {
                                    // 播放3秒后停止
                                    Thread.sleep(3000);
                                    if (ringtone.isPlaying()) {
                                        ringtone.stop();
                                    }
                                } catch (InterruptedException e) {
                                }
                            }
                        }).start();
                    }
                }
            }
        } catch (Exception exception) {
            
        }
    }
    
    public void cancelNotificaton() {
        if (this.notificationManager != null)
            this.notificationManager.cancel(notifyID);
    }
    
    public void resetNotificationCount() {
        this.notificationNum = 0;
        this.fromUsers.clear();
    }
}
